﻿namespace CommonSite.Areas.API.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using CommonHelper;
    using CommonLibrary;
    using CommonSite.Areas.API.Models;
    using CommonLibrary.Models;
    using BLToolkit.Data;
    using BLToolkit.Data.Linq;
    using BLToolkit.DataAccess;
    using System.Text;
    
    public class ControlController : BaseAPIController
    {
        public ActionResult GetUsers(string dept, string position, string username)
        {
            using (CommonDatabase db = new CommonDatabase())
            {
                dept = dept.IsNullOrWhiteSpace() ? "": dept.Trim();
                position = position.IsNullOrWhiteSpace() ? "": position.Trim();
                username = username.IsNullOrWhiteSpace() ? "": username.Trim();

                var dt = db.SetCommand(
@"select t1.*, t2.UserName, t3.Name OrgName, t4.Name PositionName, t5.UserName ParentUserName from sys_UserOrgPosition t1
	inner join sys_UserInfo t2 on t1.UserId = t2.UserId
	inner join sys_Org t3 on t1.OrgId = t3.Id
	inner join sys_Position t4 on t1.PositionId = t4.Id
	left join sys_UserInfo t5 on t1.ParentUserId = t5.UserId
where t2.UserName like '%'||@username||'%' and t3.Name like '%'||@org||'%' and t4.Name like '%'||@position||'%';",
                                db.Parameter("@username", username),
                                db.Parameter("@org", dept),
                                db.Parameter("@position", position))
                           .ExecuteDataTable();

                var query = (from System.Data.DataRow p in dt.Rows
                             select new UserOrgPosition
                             {                                 
                                 UserId = CryptHelper.Encrypt(p["userid"]),
                                 UserName = p["username"].ToString(),
                                 OrgId = CryptHelper.Encrypt(p["orgid"]),
                                 Org = p["orgname"].ToString(),
                                 PositionId = CryptHelper.Encrypt(p["positionid"]),
                                 Position = p["positionname"].ToString(),
                                 ParentUserId = p["parentuserid"] == null ? null : CryptHelper.Encrypt(p["parentuserid"]),
                                 ParentUserName = p["parentusername"].ToString()
                             }).ToList();

                return Success(new
                {
                    Total = query.Count,
                    Rows = query
                });
            }
        }
    }
}
